// pages/SubmitOrder/SubmitOrder.js
const db = wx.cloud.database()
const addresdata = db.collection('addresses');
Page({
    data: {
        userName: "", // 收货人姓名
        telNumber: "", // 联系电话
        address: "", // 收货地址
        submitted: false, // 是否已提交
        showPaymentSheet: false,
        paymentMethods: [{
                value: 'wechat',
                label: '微信支付',
                color: '#09bb07',
                buttonText: '微信支付'
            },
            {
                value: 'alipay',
                label: '支付宝支付',
                color: '#1677ff',
                buttonText: '支付宝支付'
            },
            {
                value: 'bank',
                label: '银行转账',
                color: '#666',
                buttonText: '银行转账支付'
            }
        ],
        selectedPayment: {},
        stores: [],
        totalPrice: 0,
        totalQuantity: 0,
    },

    // 返回上一页

    onShow() {
        // 每次页面显示时，从本地缓存中加载商品信息
        const stores = wx.getStorageSync('stores');
        if (stores) {
            this.setData({
                stores: stores
            }, () => {
                this.calculateTotal();
            });
        }
    },

    calculateTotal: function () {
        const {
            stores
        } = this.data;
        let totalPrice = 0;
        let totalQuantity = 0;
        if (stores && stores.length > 0) {
            totalPrice = stores.reduce((sum, item) => sum + (item.price * item.quantity), 0);
            totalQuantity = stores.reduce((sum, item) => sum + item.quantity, 0);
        }
        this.setData({
            totalPrice,
            totalQuantity
        });
    },
    gotoaddress() {
        const {
            stores
        } = this.data;
        // 将商品信息编码并传递到地址页
        const encodedStores = encodeURIComponent(JSON.stringify(stores));
        wx.navigateTo({
            url: `/pages/address/address?stores=${encodedStores}`,
        });
    },


    // 显示支付方式弹窗
    showPaymentSheet() {
        this.setData({
            showPaymentSheet: true
        });
    },

    // 关闭支付方式弹窗
    onClosePaymentSheet() {
        this.setData({
            showPaymentSheet: false
        });
    },

    // 选择支付方式
    onPaymentChange(event) {
        const value = event.detail;
        const selected = this.data.paymentMethods.find(item => item.value === value);
        this.setData({
            selectedPayment: selected,
            showPaymentSheet: false
        });
    },

    fanhui: function () {
        const {
            userName,
            telNumber,
            address
        } = this.data;



        // 遍历 stores 逐个上传订单
        this.data.stores.forEach(item => {
            const order = {
                ...item,
                username: userName,
                phonenumber: telNumber,
                address: address,
                status: '待付款'
            };

            // 删除可能的冲突字段
            delete order._id;
            delete order._openid;

            db.collection('orderlist').add({
                data: order,
                success: (res) => {
                    wx.showToast({
                        title: "订单已保存为待付款",
                        icon: 'success'
                    });
                    wx.removeStorageSync('stores'); // 新增清除本地存储
                    wx.navigateTo({
                        url: '/pages/Completion/Completion',
                    });
                },
                fail: (err) => {
                    console.error('提交失败:', err);
                    wx.showToast({
                        title: "提交失败",
                        icon: 'none'
                    });
                }
            });
        });
    },

    // 新增的 addSingleOrder 方法（替代原来的 addfun）
    addSingleOrder(name, number, address, status) {
        this.data.stores.forEach(item => {
            const order = {
                ...item,
                username: name,
                phonenumber: number,
                address: address,
                status: status
            };

            // 删除可能冲突的字段
            delete order._id;
            delete order._openid;

            db.collection('orderlist').add({
                data: order,
                success: (res) => {
                    wx.showToast({
                        title: "订单提交成功",
                        icon: 'success'
                    });
                    wx.removeStorageSync('stores'); // 清除本地存储
                    wx.navigateTo({
                        url: '/pages/Completion/Completion'
                    });
                },
                fail: (err) => {
                    console.error('提交失败:', err);
                    wx.showToast({
                        title: "提交失败",
                        icon: 'none'
                    });
                }
            });
        });
    },

    // 修改后的 submitForm 方法
    submitForm: function () {
        const {
            userName,
            telNumber,
            address,
            submitted
        } = this.data;

        if (submitted) {
            wx.showToast({
                title: '请勿重复提交',
                icon: 'none'
            });
            return;
        }


        this.setData({
            submitted: true
        });
        this.addSingleOrder(userName, telNumber, address, '待收货');
    },

    // 修改后的 onLoad 方法（清理传入数据）
    onLoad(options) {
        // 处理从地址页传递的地址数据
        if (options.addres) {
            const decodedObj = decodeURIComponent(options.addres);
            const myaddres = JSON.parse(decodedObj);
            console.log(myaddres, '从地址页传递的地址数据');
            this.setData({
                userName: myaddres.name,
                telNumber: myaddres.phone,
                address: myaddres.address
            });
        } else {
            // 尝试获取默认地址
            addresdata.where({
                isDefault: true
            }).get().then(res => {
                if (res.data.length > 0) {
                    const defaultAddress = res.data[0];
                    this.setData({
                        userName: defaultAddress.name,
                        telNumber: defaultAddress.phone,
                        address: defaultAddress.address
                    });
                } else {
                    // 没有默认地址时，设置为空字符串或提示用户
                    this.setData({
                        userName: '',
                        telNumber: '',
                        address: ''
                    });
                    wx.showToast({
                        title: '请设置默认收货地址',
                        icon: 'none'
                    });
                }
            }).catch(err => {
                console.error('获取默认地址失败:', err);
                wx.showToast({
                    title: '获取默认地址失败',
                    icon: 'none'
                });
            });
        }

        // 处理从商品页传递的商品数据
        if (options.items) {
            const items = JSON.parse(decodeURIComponent(options.items));
            // 清理可能存在的冲突字段
            const cleanItems = items.map(item => {
                delete item._id;
                delete item._openid;
                return item;
            });

            this.setData({
                stores: cleanItems
            }, () => {
                this.calculateTotal();
            });
        }

        // 设置默认支付方式
        this.setData({
            selectedPayment: this.data.paymentMethods[0]
        });
    },
    onUnload: function () {
        wx.removeStorageSync('stores');
    }
});